/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.utils;

import org.tianyun.cloud.common.dto.CursorPageResult;

import java.util.List;
import java.util.function.Function;

/**
 * CursorPageBuilder
 *
 * @auther ebert_chan
 */
public class CursorPageBuilder<T> {

    // 每页显示记录数，默认10条
    private int pageSize;

    // 偏移量，首页不用传，请求下一页时回传接口返回的值
    private Long offset;

    // 结果集列表
    private List<T> result;

    // 获取偏移量函数
    private Function<T, Long> offsetPropertyGetter;

    public CursorPageBuilder(int pageSize, Long offset) {
        this.offset = offset;
        this.pageSize = Math.max(1, pageSize);
    }

    public CursorPageBuilder<T> setResult(List<T> result) {
        return this.setResult(result, null);
    }

    public CursorPageBuilder<T> setResult(List<T> result, Function<T, Long> offsetPropertyGetter) {
        this.result = result;
        this.offsetPropertyGetter = offsetPropertyGetter;
        return this;
    }

    public Long getOffset() {
        return offset;
    }

    public void setOffset(Long offset) {
        this.offset = offset;
    }

    public int getPageSize() {
        return pageSize;
    }

    public List<T> getResult() {
        return result;
    }

    public CursorPageResult<T> build() {
        CursorPageResult<T> pageResult = new CursorPageResult<T>();
        pageResult.setPageSize(pageSize);
        pageResult.setResult(result);
        pageResult.setOffset(offset);
        if (result != null && !result.isEmpty() && offsetPropertyGetter != null) {
            pageResult.setOffset(offsetPropertyGetter.apply(result.get(result.size() - 1)));
        }
        return pageResult;
    }

}
